import React, { useState, useEffect } from 'react';
import MarkdownRenderer from './MarkdownRenderer';
import { parseMarkdownMetadata, generateTableOfContents, calculateReadingTime } from '../utils/markdownUtils';
import './MarkdownViewer.css';

interface MarkdownViewerProps {
  content: string;
  showMetadata?: boolean;
  showToc?: boolean;
  showReadingTime?: boolean;
  enableCopy?: boolean;
  className?: string;
}

const MarkdownViewer: React.FC<MarkdownViewerProps> = ({
  content,
  showMetadata = true,
  showToc = true,
  showReadingTime = true,
  enableCopy = true,
  className = ''
}) => {
  const [metadata, setMetadata] = useState<any>({});
  const [toc, setToc] = useState<any[]>([]);
  const [readingTime, setReadingTime] = useState(0);
  const [showTocPanel, setShowTocPanel] = useState(false);

  useEffect(() => {
    const { metadata: parsedMetadata, content: cleanContent } = parseMarkdownMetadata(content);
    setMetadata(parsedMetadata);
    
    const tocData = generateTableOfContents(cleanContent);
    setToc(tocData);
    
    const time = calculateReadingTime(cleanContent);
    setReadingTime(time);
  }, [content]);

  const handleTocClick = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
    setShowTocPanel(false);
  };

  const renderTocItem = (item: any, level: number = 0) => (
    <div key={item.id} className={`toc-item level-${level}`}>
      <a
        href={`#${item.id}`}
        onClick={(e) => {
          e.preventDefault();
          handleTocClick(item.id);
        }}
        className="toc-link"
      >
        {item.title}
      </a>
      {item.children && item.children.length > 0 && (
        <div className="toc-children">
          {item.children.map((child: any) => renderTocItem(child, level + 1))}
        </div>
      )}
    </div>
  );

  return (
    <div className={`markdown-viewer ${className}`}>
      {/* 元数据头部 */}
      {showMetadata && Object.keys(metadata).length > 0 && (
        <div className="markdown-header">
          {metadata.title && <h1 className="markdown-title">{metadata.title}</h1>}
          {metadata.description && <p className="markdown-description">{metadata.description}</p>}
          
          <div className="markdown-meta">
            {metadata.author && (
              <span className="meta-item">
                <span className="meta-label">作者:</span>
                <span className="meta-value">{metadata.author}</span>
              </span>
            )}
            {metadata.date && (
              <span className="meta-item">
                <span className="meta-label">日期:</span>
                <span className="meta-value">{metadata.date}</span>
              </span>
            )}
            {metadata.category && (
              <span className="meta-item">
                <span className="meta-label">分类:</span>
                <span className="meta-value">{metadata.category}</span>
              </span>
            )}
            {metadata.tags && metadata.tags.length > 0 && (
              <span className="meta-item">
                <span className="meta-label">标签:</span>
                <div className="tags">
                  {metadata.tags.map((tag: string, index: number) => (
                    <span key={index} className="tag">{tag}</span>
                  ))}
                </div>
              </span>
            )}
            {showReadingTime && (
              <span className="meta-item">
                <span className="meta-label">阅读时间:</span>
                <span className="meta-value">{readingTime} 分钟</span>
              </span>
            )}
          </div>
        </div>
      )}

      {/* 工具栏 */}
      <div className="viewer-toolbar">
        {showToc && toc.length > 0 && (
          <button
            className="toolbar-btn"
            onClick={() => setShowTocPanel(!showTocPanel)}
            title="显示目录"
          >
            📋 目录
          </button>
        )}
        {enableCopy && (
          <button
            className="toolbar-btn"
            onClick={() => navigator.clipboard.writeText(content)}
            title="复制内容"
          >
            📋 复制
          </button>
        )}
      </div>

      <div className="viewer-content">
        {/* 目录面板 */}
        {showToc && toc.length > 0 && showTocPanel && (
          <div className="toc-panel">
            <div className="toc-header">
              <h3>目录</h3>
              <button
                className="toc-close"
                onClick={() => setShowTocPanel(false)}
              >
                ×
              </button>
            </div>
            <div className="toc-content">
              {toc.map((item) => renderTocItem(item))}
            </div>
          </div>
        )}

        {/* 主要内容 */}
        <div className="markdown-main">
          <MarkdownRenderer
            content={content}
            enableCopy={false}
            className="viewer-markdown"
          />
        </div>
      </div>
    </div>
  );
};

export default MarkdownViewer;
